﻿using System;

namespace CrmClient.QueryConvert
{
    internal class PropertyMap
    {
        public bool IsMappedToCrmEntity { get; private set; }

        public Type Type { get; private set; }
        public string ClassPropName { get; private set; }

        public CrmAttrName CrmAttr { get; private set; }
        public object ConstantValue { get; private set; }

        public PropertyMap(string propertyName, Type type, object constantValue)
        {
            IsMappedToCrmEntity = false;
            ClassPropName = propertyName;
            Type = type;
            ConstantValue = constantValue;
        }

        public PropertyMap(CrmAttrName crmAttrName, string propertyName, Type type)
            : this(propertyName, type, null)
        {
            CrmAttr = crmAttrName;
            IsMappedToCrmEntity = true;
        }

        public override bool Equals(object obj)
        {
            bool res = false;
            if (obj is PropertyMap)
            {
                if (((PropertyMap)obj).IsMappedToCrmEntity && this.IsMappedToCrmEntity)
                    res = ((PropertyMap)obj).CrmAttr.Equals(this.CrmAttr);
                else if (!((PropertyMap)obj).IsMappedToCrmEntity && !this.IsMappedToCrmEntity)
                    res = ((PropertyMap)obj).Type == this.Type && ((PropertyMap)obj).ClassPropName == this.ClassPropName;
            }
            return res;
        }
        public override int GetHashCode()
        {
            if (IsMappedToCrmEntity)
                return CrmAttr.GetHashCode();
            else
                return unchecked(23 * ClassPropName.GetHashCode() * Type.GetHashCode());
        }
        public override string ToString()
        {
            return string.Format("{0} -> {1}", CrmAttr, ClassPropName);
        }

        public PropertyMap Clone()
        {
            if (IsMappedToCrmEntity)
                return new PropertyMap(CrmAttr, ClassPropName, Type);
            return new PropertyMap(ClassPropName, Type, ConstantValue);
        }
    }
}
